# -*- coding: utf-8 -*-
# @Time    : 2019/11/4 16:29
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
# @File    : yield_from_simple_example.py

final_result = {}


def sales_num(pro_num):
    # 子生成器，接受商品名称
    total = 0
    nums = []
    while True:
        x = yield  # 利用委托生成器的双向通道接受调用方传入的值
        print(pro_num+"销量:", x)
        if not x:
            break
        total += x
        nums.append(x)
    return total, nums  # 返回到final_result[key] = yield from sales_num(key)


def middle(key):
    # 委托生成器，接受商品的名称
    while True:
        # 将子生成器和调用方生成双向通信通道,已经做了try，except提取了StopIteration
        final_result[key] = yield from sales_num(key)
        print(key + "销量统计完成！")


# 需求，商品和销量，利用生成器，将结果形式进行改变
def main():
    # 调用方
    data_sets = {
        "苹果手机": [1200, 1500, 3000],
        "御泥坊面膜": [28, 55, 98, 108],
        "恒源祥毛衣": [280, 560, 778, 70],
    }
    for key, data_set in data_sets.items():
        print("start key", key)
        m = middle(key)  # 委托生成器
        m.send(None)  # 预激middle协程，启动生成器
        for value in data_set:  # [1200, 1500, 3000]
            m.send(value)  # 利用委托生成器的双向通道将值发送到子生成器中
        m.send(None)
        print("final_result:", final_result)


if __name__ == '__main__':
    main()